<template>
    <div>
<!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert :closable="false" title="添加商品信息" center type="info" show-icon></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
    <el-step title="基本信息"></el-step>
    <el-step title="商品参数"></el-step>
    <el-step title="商品属性"></el-step>
    <el-step title="商品图片"></el-step>
    <el-step title="商品内容"></el-step>
    <el-step title="完成"></el-step>
</el-steps>
<el-form :model="addForm" :rules="addFormRules"
 ref="addFormRef" label-width="100px" label-position="top">
<el-tabs v-model="activeIndex" :tab-position="tabPosition"
  :before-leave="beforeLeave" @tab-click="tabClicked">
    <el-tab-pane label="基本信息" name="0">
      <el-form-item label="商品名称" prop="goods_name">
        <el-input v-model="addForm.goods_name"></el-input>
      </el-form-item>
       <el-form-item label="商品价格" prop="goods_price">
        <el-input v-model="addForm.goods_price" type="number"></el-input>
      </el-form-item>
       <el-form-item label="商品数量" prop="goods_number">
        <el-input v-model="addForm.goods_number" type="number"></el-input>
      </el-form-item>
       <el-form-item label="商品重量" prop="goods_weight">
        <el-input v-model="addForm.goods_weight" type="number"></el-input>
      </el-form-item>
        <el-form-item label="选择商品分类" prop="goods_cat">
      <el-cascader v-model="addForm.goods_cat" :options="paramsData"
    :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name',
     children: 'children'}"
    clearable @change="handleChange"></el-cascader>
      </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品参数" name="1">
      <el-form-item :label="item.attr_name" v-for="item in manydata" :key="item.attr_id">
        <el-checkbox-group v-model="item.attr_vals"><!-- 复选框组 -->
          <el-checkbox v-for="(cb, i) in item.attr_vals" :key="i"
          :label="cb" border>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品属性" name="2">
      <el-form-item :label="item.attr_name" v-for="item in onlydata" :key="item.attr_id">
         <el-input v-model="item.attr_vals"></el-input>
      </el-form-item>
    </el-tab-pane>
    <el-tab-pane label="商品图片" name="3">
   <el-upload :action="action"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  list-type="picture" :headers="headerObj"
  :on-success="handlesuccess">
  <el-button size="small" type="primary">点击上传</el-button>
</el-upload>
    </el-tab-pane>
    <el-tab-pane label="商品内容" name="4">
      <!-- 富文本编辑器 -->
  <quill-editor
    ref="myQuillEditor"
    v-model="addForm.goods_introduce"
  />
  <el-button type="primary" class="addbut" @click="addGoods">添加商品</el-button>
    </el-tab-pane>
  </el-tabs>
</el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisable"
    width="30%" class="dialogImg" center>
  <img :src="previewPath" alt="图片预览" class="previewImg">
    </el-dialog>
    </div>
</template>
<script>
import _ from 'lodash'/* 导入lodash */
export default {
  data () {
    return {
      activeIndex: '0',
      tabPosition: 'left',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类
        goods_cat: [],
        pics: [], // 储存图片临时地址
        // 商品的详情描述
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      paramsData: [], // 分类数据列表
      manydata: [], // 参数列表
      onlydata: [], // 属性列表
      // 上传图片的URL地只
      action: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传组件的headers请求头对象
      headerObj: {
        // 请求的token值
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '', // 查看预览图片的URL地址
      previewVisable: false // 控制预览框的现实与隐藏

    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200) {
        return this.$message.error('请求分类数据失败');
      }
      this.paramsData = res.data;
      // console.log(this.paramsData)
    },
    handleChange () {
      // 选择器选中项变化处罚的函数
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    beforeLeave (activeNAme, oldActiveName) {
      // activeName是即将静茹的标签页的名字，old是即将离开的 return false就会阻止标签页的切换
      if (oldActiveName === '0' &&
    this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false;
      }
      return true;
    },
    async tabClicked () {
      console.log(this.activeIndex);
      if (this.activeIndex === '1') {
        // 访问动态参数面板
        // console.log('冬天参数')
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } });
        if (res.meta.status !== 200) {
          return this.$message.error('请求动态参数失败');
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        })
        this.manydata = res.data;
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } });
        if (res.meta.status !== 200) {
          return this.$message.error('请求动态参数失败');
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ');
        })
        this.onlydata = res.data;
        console.log(res.data);
      }
    },
    handlePreview (file) {
      // 处理图片预览
      // console.log(file)
      this.previewPath = file.response.data.url;
      this.previewVisable = true;
    },
    handleRemove (file) {
      // 处理移除图片的操作
      // console.log(file)
      // 将要删除的图片的临时路径
      const deletePath = file.response.data.tmp_path;
      // 索引值
      const i = this.addForm.pics.findIndex(x => x.pic === deletePath)
      this.addForm.pics.splice(i, 1); // 从临时图片中删除已经被删除的图片的临时地址
      console.log(this.addForm)
    },
    handlesuccess (response) {
      // 监听图片上穿成功的事件
      console.log(response);
      // 拼接得到一个图片对象
      // 将图片信息对象push到pics中
      const pic = { pic: response.data.tmp_path }
      this.addForm.pics.push(pic)
      console.log(this.addForm)
    },
    addGoods () {
      // 添加商品
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的内容');
        }
        // 处理动态参数和静态属性
        this.manydata.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        this.onlydata.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        // 发起请求,商品名称唯一
        const { data: res } = await this.$http.post('goods', form);
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加成功');
        this.$router.push('/goods')
      })
    }

  },
  created () {
    this.getCateList();
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null
    }

  }

}
</script>
<style lang="less" scoped>
.el-checkbox{
  margin: 0 5px 0 0;
}
.previewImg{
  width: 100%;
  height: 450px;
  justify-content: center;
  align-items: center;

}
.dialogImg{
  display: flex;
}
.addbut{
  position: relative;
  margin-top: 15px;
  left: 90%;
}

</style>
